import { Response } from 'express';
import prisma from '../lib/prisma';
import { Submission } from '../types/prisma-types';
import { AuthenticatedRequest } from '../types/auth';
import { TeachingAnalysisService } from '../services/teachingAnalysisService';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';

export const teachingAnalysisController = {
  // 获取教师教学评估数据
  async getTeacherEvaluation(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { teacherId } = req.params;

      // 验证是否有权限查看该教师的数据
      if (req.user.role !== 'ADMIN' && req.user.id !== teacherId) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权访问此教师的数据');
      }

      const evaluationData = await TeachingAnalysisService.getTeacherEvaluation(teacherId);

      res.json({
        success: true,
        data: evaluationData
      });
    } catch (error) {
      logger.error('获取教师教学评估数据失败', {
        context: 'teachingAnalysisController.getTeacherEvaluation',
        error
      });
      throw error;
    }
  },

  // 获取教学建议
  async getTeachingRecommendations(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { teacherId } = req.params;

      // 验证是否有权限查看该教师的数据
      if (req.user.role !== 'ADMIN' && req.user.id !== teacherId) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权访问此教师的数据');
      }

      const recommendations = await TeachingAnalysisService.getTeachingRecommendations(teacherId);

      res.json({
        success: true,
        data: recommendations
      });
    } catch (error) {
      logger.error('获取教学建议失败', {
        context: 'teachingAnalysisController.getTeachingRecommendations',
        error
      });
      throw error;
    }
  },

  // 获取指定教师在特定时间段内的教学分析数据
  async getTeacherAnalysisByPeriod(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const { teacherId } = req.params;
      const { startDate, endDate } = req.query;

      // 验证是否有权限查看该教师的数据
      if (req.user.role !== 'ADMIN' && req.user.id !== teacherId) {
        throw new ApiError(StatusCodes.FORBIDDEN, '无权访问此教师的数据');
      }

      // 验证日期参数
      if (!startDate || !endDate) {
        throw new ApiError(StatusCodes.BAD_REQUEST, '必须提供开始日期和结束日期');
      }

      // 转换日期字符串为Date对象
      const start = new Date(String(startDate));
      const end = new Date(String(endDate));

      if (isNaN(start.getTime()) || isNaN(end.getTime())) {
        throw new ApiError(StatusCodes.BAD_REQUEST, '无效的日期格式');
      }

      // 获取指定时间段内的教学数据
      const submissions = await prisma.submission.findMany({
        where: {
          question: {
            creatorId: teacherId
          },
          createdAt: {
            gte: start,
            lte: end
          }
        },
        include: {
          question: true,
          user: {
            select: {
              id: true,
              name: true
            }
          }
        }
      });

      // 计算时间段内的统计数据
      const avgScore = submissions.reduce((sum: number, sub: Submission) => sum + sub.score, 0) / submissions.length;
      const studentCount = new Set(submissions.map((sub: Submission) => sub.user.id)).size;
      const questionCount = new Set(submissions.map((sub: Submission) => sub.questionId)).size;

      res.json({
        success: true,
        data: {
          periodStats: {
            submissionCount: submissions.length,
            averageScore: avgScore,
            uniqueStudents: studentCount,
            uniqueQuestions: questionCount
          },
          submissions
        }
      });
    } catch (error) {
      logger.error('获取教师时段分析数据失败', {
        context: 'teachingAnalysisController.getTeacherAnalysisByPeriod',
        error
      });
      throw error;
    }
  }
};
